<template>
  <div class="je-setting-service-box">
    <je-panel>
      <je-panel-item region="left" v-bind="leftArea">
        <div class="platform-service-tree-box">
          <div class="platform-service-tree-operate">
            <div>快速查询</div>
            <div>
              <i class="fal fa-chevron-left" title="收起" @click="handleTreeHide"></i>
              <i class="fal fa-chevron-up" title="收起" @click="handleTreePackUp"></i>
              <i class="fal fa-sync" title="刷新" @click="handleRefreshData"></i>
            </div>
          </div>
          <je-tree
            ref="refServiceTree"
            :search="{ style: 'height:40px;' }"
            size="mini"
            :loading="treeLoading"
            :data="treeData"
            :tree-config="{
              trigger: 'cell-dblclick',
              rowField: 'id',
              parentField: 'parent',
              expandAllRow: true,
            }"
            @current-change="handleTreeSelect"
            @search-select="handleTreeSearch"
          ></je-tree>
        </div>
      </je-panel-item>
      <je-panel-item>
        <div class="setting-service-table">
          <div class="setting-service-clear">
            <je-button :disabled="!serviceConfig" @click="handleRemoveAllCache"
              >清理全部缓存</je-button
            >
            <je-button :disabled="!serviceConfig" icon="fal fa-remove" @click="hanldRemoveCacheIds"
              >清理缓存</je-button
            >
          </div>
          <je-table
            ref="refService"
            border
            auto-resize
            show-overflow="ellipsis"
            keep-source
            :draggable="false"
            :size="tableSize"
            :loading="loading"
            show-header-overflow
            :store="serviceStore"
            resizable
            header-align="center"
            align="center"
            :scroll-y="{ mode: 'wheel' }"
            :auto-load="true"
          >
            <je-column type="checkbox" width="60"></je-column>
            <je-column type="seq" width="60" title="No."></je-column>
            <je-column
              field="SERVICE_NAME"
              name="SERVICE_NAME"
              width="150"
              title="服务名称"
            ></je-column>
            <je-column field="VERSION" name="VERSION" min-width="100" title="版本"></je-column>
            <je-column
              field="SCHEMAS_LENGTH"
              name="SCHEMAS_LENGTH"
              min-width="100"
              title="契约数量"
            ></je-column>
            <je-column field="APP_ID" name="APP_ID" min-width="150" title="APP_ID"></je-column>
            <je-column field="ENVIRONMENT" name="" min-width="150" title="启动模式"></je-column>
            <je-column field="LEVEL" name="LEVEL" min-width="120" title="LEVEL"></je-column>
            <je-column
              field="FRAMEWORK"
              name="FRAMEWORK"
              min-width="155"
              title="FRAMEWORK"
            ></je-column>
          </je-table>
        </div>
      </je-panel-item>
    </je-panel>
  </div>
</template>

<script>
  import { defineComponent, reactive, toRefs, onMounted } from 'vue';
  import { Panel, Tree, Grid, Data, Button, Modal } from '@jecloud/ui';
  import { getDictionaryTree } from '@/api/index';
  import { isNotEmpty, ajax } from '@jecloud/utils';
  export default defineComponent({
    name: 'PlatformService',
    components: {
      JePanel: Panel,
      JePanelItem: Panel.Item,
      JeTree: Tree,
      JeTable: Grid,
      JeColumn: Grid.Column,
      JeButton: Button,
    },
    setup() {
      const state = reactive({
        leftArea: {
          size: 230,
          split: true,
          collapsible: true,
          collapsed: false,
          style: { borderRight: '1px solid #ecedf0' },
        },
        refServiceTree: null,
        treeData: null, //树结构数据
        treeLoading: false,
        serviceConfig: null, //服务契约配置信息
        tableSize: 'small', //紧凑
        loading: false,
        serviceStore: Data.Store.useGridStore({
          data: [],
        }),
        refService: null, //数据对象
      });
      const methods = {
        handleTreeHide() {
          state.leftArea.collapsed = !state.leftArea.collapsed;
        },
        handleTreePackUp() {
          state.refServiceTree.clearTreeExpand();
        },
        handleRefreshData() {
          methods.getTreeData();
        },
        handleTreeSelect({ row }) {
          if (isNotEmpty(row.nodeInfo)) {
            const curNodeIofo = JSON.parse(row.nodeInfo);
            if (state.serviceConfig && state.serviceConfig.instanceId == curNodeIofo.instanceId) {
              state.serviceConfig = null;
              state.serviceStore.loadData([]);
            } else {
              state.serviceConfig = curNodeIofo;
              methods.getServiceData(state.serviceConfig);
            }
          } else {
            state.serviceConfig = null;
            state.serviceStore.loadData([]);
          }
        },
        handleTreeSearch({ row }) {
          methods.handleTreeSelect({ row: row, newValue: true });
        },
        getServiceData(seveceConfig) {
          //获取服务数据
          if (seveceConfig?.isInstance) {
            state.loading = true;
            ajax({
              url: seveceConfig.getUrl,
              headers: seveceConfig.headers,
              method: 'GET',
            }).then((res) => {
              state.loading = false;
              if (res.success) {
                state.serviceStore.loadData(res.data.rows);
              } else {
                state.serviceStore.loadData([]);
              }
            });
          }
        },
        onPageChange() {
          state.serviceConfig && methods.getServiceData(state.serviceConfig);
        },
        getTreeData() {
          state.treeLoading = true;
          const strDataParam = [
            {
              ddCode: 'JE_MICROSERVICE_APPID',
              ddName: '所属服务',
              rootId: null,
              async: false,
              params: {},
              j_query: { custom: [], order: [], _types: [] },
              nodeInfo: 'AFFILIATED_SERVICES',
            },
          ];
          const treeParams = {
            node: 'ROOT',
            onlyItem: false,
            excludes: 'checked',
            strData: JSON.stringify(strDataParam),
          };
          getDictionaryTree(treeParams).then((res) => {
            state.treeLoading = false;
            state.treeData = res;
            setTimeout(() => {
              const treeChild = res[0].children;
              treeChild.forEach((treeItem) => {
                const row = state.refServiceTree.getRowById(treeItem.id);
                if (row) {
                  state.refServiceTree.setTreeExpand4Path({ row, expand: true }).then((row) => {
                    // state.refServiceTree.setSelectRow(row);
                    state.refServiceTree.scrollToRow(row);
                  });
                }
              });
            }, 200);
          });
        },
        hanldRemoveCacheIds() {
          //按id清除缓存
          const selectRecords = state.refService.getSelectedRecords();
          if (selectRecords.length == 0) {
            Modal.alert('请先选中清理的服务！', 'warning');
          } else {
            Modal.confirm({
              title: '清理',
              content: `是否确认清理所选服务缓存？`,
              okButton: () => {
                let removeKeyArr = [];
                if (state.serviceConfig.isInstance) {
                  selectRecords.forEach((record) => {
                    if (!removeKeyArr.includes(record.SERVICE_NAME)) {
                      removeKeyArr.push(record.SERVICE_NAME);
                    }
                  });
                  ajax({
                    url: state.serviceConfig.clearUrl,
                    headers: state.serviceConfig.headers,
                    method: 'GET',
                    params: { microKey: removeKeyArr.join(',') },
                  }).then((res) => {
                    Modal.notice({ content: '清理成功', status: 'success' });
                    methods.getServiceData(state.serviceConfig);
                  });
                }
              },
            });
          }
        },
        handleRemoveAllCache() {
          //清理全部缓存
          Modal.confirm({
            title: '清理',
            content: `是否确认清理所有服务缓存？`,
            okButton: () => {
              if (state.serviceConfig.isInstance) {
                ajax({
                  url: state.serviceConfig.clearUrl,
                  headers: state.serviceConfig.headers,
                  method: 'GET',
                  params: { microKey: 'all' },
                }).then((res) => {
                  Modal.notice({ content: '清理成功', status: 'success' });
                  methods.getServiceData(state.serviceConfig);
                });
              }
            },
          });
        },
      };
      onMounted(() => {
        methods.getTreeData();
      });
      return {
        ...toRefs(state),
        ...methods,
      };
    },
  });
</script>
<style scoped lang="less">
  .je-setting-service-box {
    width: 100%;
    height: 100%;
    padding: 14px;

    .platform-service-tree-box {
      width: 100%;
      height: 100%;
      padding: 10px 12px 50px;
      .platform-service-tree-operate {
        width: 100%;
        height: 32px;
        display: flex;
        align-items: center;
        justify-content: space-between;
        padding: 0 6px;
        margin-bottom: 10px;
        i {
          cursor: pointer;
          margin-left: 8px;
        }
      }
    }
    .setting-service-table {
      width: 100%;
      height: 100%;
      padding: 10px;
      overflow: hidden;
      .setting-service-clear {
        display: flex;
        justify-content: end;
        margin-bottom: 10px;
        button {
          color: #3f3f3f;
          background-color: #ffffff;
          border-color: #d9d9d9;
        }
        button:last-child {
          margin-left: 10px;
        }
      }
      /deep/ .je-panel-wrapper {
        height: calc(100% - 32px) !important;
      }
    }
  }
</style>
